package com.lumlord.common.spring;

import java.lang.reflect.AnnotatedElement;
import java.util.Arrays;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lumlord.common.annotation.Api;
import com.lumlord.common.domain.Result;
import com.lumlord.common.exception.BusinessException;

@ControllerAdvice(annotations = Api.class)
public class ApiResultHandler implements ResponseBodyAdvice {

	private ThreadLocal<ObjectMapper> mapperThreadLocal = ThreadLocal.withInitial(ObjectMapper::new);

	private static final Class[] annos = {Api.class};

	/**
	 * 对所有RestController的接口方法进行拦截
	 */
	@Override
	public boolean supports(MethodParameter returnType, Class converterType) {
		AnnotatedElement element = returnType.getAnnotatedElement();
		return Arrays.stream(annos).anyMatch(anno -> anno.isAnnotation() && element.isAnnotationPresent(anno));
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
			Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
		if(body instanceof Result) {
			try {
				throw new BusinessException("Result unsupport return ,please change new map!");
			} catch (BusinessException e) {
				e.printStackTrace();
			}
			return Result.error("Result unsupport return ,please change new map!");
		}
		
		response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes();
		HttpServletRequest req = requestAttributes.getRequest();
		Map ret = Result.success(body);
		ret.put("executeTime", req.getAttribute("executeTime"));
		ret.put("design", req.getAttribute("design"));
		return ret;
	}

}